package com.jiangxjsy.core.jwt;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * wukong-crm-master
 * 蒋胜宇
 * 2025/5/29 16:10
 */

public class RsaHelper {
    /**
     * 获取公钥
     *
     * @param fileName 公钥文件名
     * @return PublicKey
     * @throws Exception IOException
     */
    public static PublicKey getPublicKey(String fileName) throws Exception {
        byte[] bytes = Files.readAllBytes(new File(fileName).toPath());
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(bytes);
        return KeyFactory.getInstance("RSA").generatePublic(x509EncodedKeySpec);
    }

    /**
     * 获取私钥
     *
     * @param fileName 私钥文件名
     * @return PrivateKey
     * @throws Exception IOException
     */
    public static PrivateKey getPrivateKey(String fileName) throws Exception {
        byte[] bytes = Files.readAllBytes(new File(fileName).toPath());
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(bytes);
        return KeyFactory.getInstance("RSA").generatePrivate(pkcs8EncodedKeySpec);
    }

    /**
     * 生成密钥对
     *
     * @param publicKeyPath 公钥路径
     * @param privateKeyPath 私钥路径
     * @param secret 密钥
     * @throws Exception IOException
     */
    public static void generateKey(String publicKeyPath, String privateKeyPath, String secret) throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        SecureRandom secureRandom = new SecureRandom(secret.getBytes());
        keyPairGenerator.initialize(1024, secureRandom);
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        byte[] publicBytes = keyPair.getPublic().getEncoded();
        writeFile(publicKeyPath, publicBytes);
        byte[] privateBytes = keyPair.getPrivate().getEncoded();
        writeFile(privateKeyPath, privateBytes);
    }

    /**
     * 写入文件
     *
     * @param destPath 目标文件
     * @param bytes 文件内容
     * @throws IOException IOException
     */
    private static void writeFile(String destPath, byte[] bytes) throws IOException {
        File file = new File(destPath);
        if (!file.exists()) {
            boolean ignore = file.createNewFile();
        }
        Files.write(file.toPath(), bytes);
    }
}
